#include "QUDPControl.h"

QUDPControl::QUDPControl()
{
//    us = new QUdpSocket;
//    connect(us,&QUdpSocket::readyRead,this,&QUDPControl::recvData);
}

void QUDPControl::ConnectToHost()
{
    us = new QUdpSocket(this);
    connect(us,&QUdpSocket::readyRead,this,&QUDPControl::recvData);
    bool ret =  robotAddr.setAddress(_con.ip.data());
    robotPort = _con.port;
    ret =  us->bind(robotAddr,robotPort);
    qDebug()<< ret<< us->errorString();
}


void QUDPControl::ReConnectToHost()
{
    DisConnectToHost();
    ConnectToHost();
}

void QUDPControl::DisConnectToHost()
{
    us->disconnectFromHost();
}

void QUDPControl::WriteBuff(const char *buff)
{
    us->writeDatagram(buff,sizeof(buff),robotAddr,robotPort);
//    if(us->isOpen()){
//        us->writeDatagram(buff,sizeof(buff),QHostAddress(_con.ip.data()),_con.port);
//    }else{
//        qWarning("UDP并未打开!");
//    }
}

void QUDPControl::recvData()
{
    while(us->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(us->pendingDatagramSize());
        us->readDatagram(datagram.data(),datagram.size(),&robotAddr,&robotPort);
        if(datagram.size() > 3)
        {
            QString QD = QString(datagram);
            cout<<"接收到数据:"<<QD.toLocal8Bit().toStdString()<<endl;
            _sigUpdate(QD.toLocal8Bit().toStdString());
            QStringList runInfos = QD.split(",");
            if(runInfos.size() >= 6)
            {
                //
//                if(_robot->rgsoStatus < 0) // 私服状态未启动
//                {
//                }
            }
        }
    }
}
